<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 与 添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="eMail" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
            </el-button>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="eMail">
          <el-input v-model="addForm.eMail"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="eMail">
          <el-input v-model="editForm.eMail"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框@close="editDialogClose" -->
    <el-dialog title="分配权限" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClose">
      <div>
        <p>当前用户：{{ userInfo.username }}</p>
        <p>当前角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：
          <template>
            <el-select v-model="selectedRole" placeholder="请选择">
              <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
 
<script>
export default {
  name: 'Users',
  data() {
    // 邮箱的自定义校验规则
    var checkeMail = (rule, value, callback) => {
      const regeMail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/

      if (regeMail.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法邮箱！'))
    };
    // 手机号的自定义验证规则
    let checkemobile = (rule, value, callback) => {
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
      if (regMobile.test(value)) return callback()

      callback(new Error('请输入合法的手机号！'))
    }
    return {
      queryInfo: {  // 获取用户列表参数
        query: '',
        pagenum: 1,  // 页数
        pagesize: 2,  // 数据条数
      },
      userList: [],  // 用户数据
      total: 0,  // 总数据条数
      //mg_state: null,  // 状态开关控制
      addDialogVisible: false,  // 添加用户对话框控制显示
      addForm: {  //添加用户的表单数据
        username: '',  // 用户名
        password: '',  // 密码
        mobile: '',  // 手机号
        eMail: '',  // 邮箱
        create_time: '',  // 创建日期
        role_name: '',  // 用户权限
      },
      // 添加用户表单验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          { require: true, min: 3, message: '长度最少3个字符！', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码！', trigger: 'blur' },
          { require: true, min: 3, message: '长度最少3个字符！', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号！', trigger: 'blur' },
          { validator: checkemobile, trigger: 'blur' }
        ],
        eMail: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkeMail, trigger: 'blur' }
        ],
      },
      editDialogVisible: false,  // 控制 修改用户对话框的 显示与隐藏
      editForm: {},  // 用户信息
      // 修改用户信息表单验证
      editFormRules: {
        mobile: [
          { required: true, message: '请输入手机号！', trigger: 'blur' },
          { validator: checkemobile, trigger: 'blur' }
        ],
        eMail: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkeMail, trigger: 'blur' }
        ]
      },
      // 控制用户权限对话框的显示与否
      setRoleDialogVisible: false,
      userInfo: {},  // 需要分配角色的用户信息
      roleList: [],  // 用户角色列表
      selectedRole: '',  // 已选中的角色
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$ajax.get('users', { params: this.queryInfo })
      if (res.meta.code !== 200) return this.$message.error('用户数据请求失败！')
      res.data.users.forEach(element => {
        element.mg_state = Boolean(element.mg_state)
      });
      this.userList = res.data.users
      this.total = res.data.totalPage
    },
    // 监听 数据条数 改变pagenum
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 开关状态 改变
    async userStateChanged(userInfo) {
      const { data: res } = await this.$ajax.put('users/revise', { uId: userInfo.id, state: userInfo.mg_state })
      if (res.meta.code !== 200) {
        this.mg_state = !this.mg_state
        return this.$message.error('用户状态更新失败！')
      }
      this.$message.success(res.meta.msg)
    },
    // 监听 添加用户对话框 关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户按钮
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$ajax.post('users/add', this.addForm)
        if (res.meta.code !== 200 || !res.meta.code) return this.$message.error(`用户添加失败`)
        this.$message.success('添加用户成功！')
        this.addDialogVisible = false  // 关闭对话框
        this.getUserList()
      })
    },
    // 展示编辑用户对话框
    async showEditDialog(id) {
      // console.log(id);
      const { data: res } = await this.$ajax.get('users/selectForId', { params: { id } })
      if (res.meta.code !== 200) return this.$message.error('用户查询失败！')
      this.editForm = res.data[0]
      this.editDialogVisible = true
    },
    // 监听 修改用户信息对话框 的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //修改用户
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$ajax.put('users/editUserInfo', this.editForm)
        if (res.meta.code !== 200) this.$message.error('修改用户失败！')
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('用户信息修改成功！')
      })
    },
    // 删除用户按钮
    async removeUserById(id) {
      // 弹框询问
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return console.log(err);
      });

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$ajax.delete('users/' + id)
      if (res.meta.code !== 200) return this.$message.error('用户删除失败！')
      this.$message.success('用户删除成功！')

      this.getUserList();
    },
    // 展示分配权限对话框
    async setRole(userInfo) {
      this.userInfo = userInfo

      const { data: res } = await this.$ajax.get('permission/roles/list')
      if (res.meta.code !== 200) return this.$message.error('用户角色信息请求失败！')
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色
    async saveRoleInfo() {
      let queryInfo = ''
      if (!this.selectedRole) return this.$message.error('请选择要分配的角色！')
      if (this.selectedRole === 1) {
        queryInfo = '管理员'
      } else {
        queryInfo = '测试'
      }
      const { data: res } = await this.$ajax.put('users/setRole', { setuserInfo: queryInfo, id: this.userInfo.id })
      if (res.meta.code !== 200) return this.$message.error('用户角色分配失败！')

      this.getUserList()
      this.$message.success('用户角色分配成功！')
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框关闭事件
    setRoleDialogClose() {
      this.selectedRole = '',
        this.userInfo = {}
    }
  },
}
</script>
 
<style lang='less' scoped>

</style>